package book;

import javax.microedition.pim.UnsupportedFieldException;

public class PageManager {

	private static final int NUM_PHRASES_PER_PAGE = 36;
	private static final int MAX_NUM_PAGES = 150;
	public static final int NO_PAGE = -1;

	private int page = NO_PAGE;

	public PageManager() {
		page = 1;
	}

	public void computePage(int phraseIndex) {
		page = phraseIndex / NUM_PHRASES_PER_PAGE + 1;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int value) {
		if (value <= 0) {
			page = 1;
		} else if (value > MAX_NUM_PAGES) {
			page = MAX_NUM_PAGES;
		} else {
			page = value;
		}
	}

	public void deletePageUnities() {
		if (page < 10) {
			page = NO_PAGE;
		} else {			
			page = page / 10;
		}
	}

	public void newNumeralEntered(int num) {
		if ((num < 0) || (num > 9)) {
			throw new UnsupportedFieldException(
					"Enter a value between 0 and 9.");
		}
		if (page == NO_PAGE) {
			page = num;
			if (num == 0) {
				page = 1;
			}
		}  else {			
			page = page * 10 + num;
		}
		if (page > MAX_NUM_PAGES) {
			page = MAX_NUM_PAGES;
		}
	}

	public int getPhraseIndex() {
		int result = 0;
		if (page != NO_PAGE) {		
			result = (page - 1) * NUM_PHRASES_PER_PAGE;
		}
		return result;
	}
}
